let index = -1;
const apiList = [];

chrome.devtools.inspectedWindow.eval("window.location", function (
  result,
  isException
) {
  if (isException) return;

  chrome.devtools.network.onRequestFinished.addListener((request, data) => {
    if (request._resourceType === "xhr" && request.response.status === 200) {
      request.getContent((content) => {
        const paramStr = request.request.postData
          ? request.request.postData.text
          : "";
        const method = request.request.method;
        const host = `${result.protocol}//${result.host}`;

        let url = request.request.url;

        if (url.indexOf(host) === -1) return;

        url = url.replace(host, "");
        url = url.split("?")[0];

        let res;
        try {
          res = content ? JSON.parse(content) : "";
        } catch (e) {
          res = "";
        }
        index++;
        apiList.push({
          index,
          method,
          url,
          res,
        });

        $("#warp").append(`<li>
            <span>${url}</span>
            <button data-index="${index}" id="btn-${index}">保存</button>
        </li>`);

        $("#btn-" + index).click(function () {
          const i = $(this).attr("data-index");
          save(i);
        });
      });
    }
  });
});

function save(index) {
  const data = apiList[index];
  $.ajax({
    url: "http://localhost:3004/api/add-interface",
    type: "post",
    data: JSON.stringify({
      isOpen: true,
      method: data.method,
      name: data.url.substr(data.url.lastIndexOf("/") + 1),
      path: data.url,
      prefix: "",
      sourceData: JSON.stringify(JSON.stringify(data.res, null, 2)),
      source: 4,
      data: data.res,
    }),
    contentType: "application/json;charset=utf-8",
    datatype: "json",
    success(res) {
      console.log(res);
      $("#error").css("display", "block");
      if (res.success) {
        $("#error").text("保存成功");
      } else {
        $("#error").text(res.errorMsg);
      }

      setTimeout(() => {
        $("#error").css("display", "none");
      }, 1500);
    },
    error(e) {
      console.log(e);
    },
  });
}
